// react里面通过ref来获取组件或者dom元素。要使用ref之前必须先调用React.createRef方法来创建一个ref
import React, { Component, createRef } from 'react'
import PropsTypes from 'prop-types'      

export default class TodoInput extends Component {
    static propsTypes = {
        btnText: PropsTypes.string,
    }
    static defaultProps = {
        btnText: 'Add'
    }
    constructor() {
        super()
        this.state = {
            inputValue: '',
        }

        // 在constructor里面创建ref
        this.inputDom = createRef()

        // this.handleAddClickCopy = this.handleAddClick.bind(this)
    }
    handleInputChange = (e) => {
        // console.log(e)
        this.setState({
            inputValue: e.currentTarget.value
        })
    }

    handleAddClick = () => {
        // 验证  需要加trim()
        if(this.state.inputValue === '') {
            return
        }
        this.props.addTodo(this.state.inputValue)
        this.setState({
            inputValue: ''
        },() => {
            // 置空（完成）之后再获取焦点
            // console.log(this.inputDom)
            this.inputDom.current.focus()
        })
    }
    // handleAddClick = (id) => {      // 箭头函数已经隐式的将this指向改变了
    //     console.log(this.state, id)
    // }
    // handleAddClick (id)  {        // 这种方式要使用bind改变this指向，不然读取不到state
    //     console.log(this.state, id)
    // }
    handleKeyUp = (e) => {
        if(e.keyCode === 13) {
            this.handleAddClick()
        }
    }
    render() {
        return (
            <div>
                <input 
                    type="text" 
                    value={this.state.inputValue} 
                    onChange={this.handleInputChange}
                    onKeyUp={this.handleKeyUp}
                    ref={this.inputDom}
                /> 
                <button onClick={this.handleAddClick}>{this.props.btnText}</button>
                {/* <button onClick={this.handleAddClickCopy}>{this.props.btnText}</button> */}
                {/* 传参方式 */}
                {/* <button onClick={this.handleAddClick.bind(this, 123)}>{this.props.btnText}</button> */}
                {/* <button onClick={() => { this.handleAddClick(123) }}>{this.props.btnText}</button> */}
            </div>
        )
    }
}
